/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd

import (
	"os"

	"gitee.com/extrame/fb-runner/app"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var invokeCfg struct {
	IsInit *bool
	Code   *string
}

// invokeCmd represents the invoke command
var invokeCmd = &cobra.Command{
	Use:   "invoke",
	Short: "调用部署合约",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 {
			code := app.GetInstalledChaincodeByName(args[0])
			if code != nil {
				if len(code) > 1 {
					logrus.Error("系统中有同名合约，请在名称后附加Package ID作为参数明确选择")
					for n, c := range code {
						logrus.Errorf("[%d]%s", n+1, c.PackageId)
					}
					os.Exit(1)
					return
				}
				if *invokeCfg.Code != "" {
					var prepends []string
					if *invokeCfg.IsInit {
						prepends = append(prepends, "--isInit", "-c")
					} else {
						prepends = append(prepends, "-c")
					}
					prepends = append(prepends, *invokeCfg.Code)
					err := app.Invoke(cfg.GetBase(), code[0], prepends)
					cobra.CheckErr(err)
				} else {
					logrus.Fatalln("输入执行内容为空")
				}
			}
		} else {
			logrus.Fatalln("未指定package名称")
		}
	},
}

func init() {
	rootCmd.AddCommand(invokeCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// invokeCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	invokeCfg.IsInit = invokeCmd.Flags().BoolP("isInit", "I", false, "该命令为初始化命令")
	invokeCfg.Code = invokeCmd.Flags().StringP("code", "c", "", "具体的执行命令内容")
}
